/*
 * @lc app=leetcode.cn id=86 lang=java
 *
 * [86] 分隔链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {

        if(head == null || head.next == null) {
            return head;
        }

        // 创建两个链表，一个存储小于 x 的节点，一个存储大于等于 x 的节点
        // 最后将两个链表连接起来
        ListNode small = new ListNode(0);
        ListNode big = new ListNode(0);

        ListNode curSmall = small;    // 定义一个指针指向small链表的尾节点
        ListNode curBig = big;         // 定义一个指针指向big链表的尾节点

        while(head != null) {
            if(head.val < x) {
                curSmall.next = head;
                curSmall = curSmall.next;
            } else {
                curBig.next = head;
                curBig = curBig.next;
            }
            head = head.next;
        }

        curBig.next = null;     // 将大于等于 x 的链表的尾节点指向 null
        curSmall.next = big.next;   // 将小于 x 的链表的尾节点指向大于等于 x 的链表的头节点

        return small.next;
    }
}
// @lc code=end

